﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;
using System.Configuration;

namespace MINERP.InfoConfig
{
    public partial class FrmAttachDB : Form
    {
        public FrmAttachDB()
        {
            InitializeComponent();
        }

        private void btnMDF_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "*.mdf|";
            openFileDialog1.ShowDialog();


            txtMdfPath.Text = openFileDialog1.FileName;
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "*.LDF|";
            openFileDialog1.ShowDialog();
            this.txtLogPath.Text = openFileDialog1.FileName;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMdfPath.Text) || string.IsNullOrEmpty(txtLogPath.Text) | string.IsNullOrEmpty(txtMdfPath.Text))
            {
                MessageBox.Show("请选择正确的数据库文件，数据库名不能为空!");
            }
            else
            {
                try
                {
                    using (SqlConnection sqlConn = new SqlConnection(ConfigurationSettings.AppSettings["SqlConnStr"].ToString()))
                    {
                        sqlConn.Open();
                        SqlCommand sqlCmd = new SqlCommand(string.Format("execute sp_attach_db @dbname =N'{0}',@filename1 =N'{1}',@filename2=N'{2}'", txtMdfPath.Text.Trim(), txtMdfPath.Text.Trim(), txtLogPath.Text.Trim()), sqlConn);
                        sqlCmd.ExecuteNonQuery();
                    }
                    MessageBox.Show("附加成功！");
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("附加失败！" + ex.Message);

                }


            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
